package com.sike.netty.im.server.handler;

import cn.hutool.json.JSONUtil;
import com.sike.netty.im.common.command.GroupChatRequestCommand;
import com.sike.netty.im.common.command.GroupChatResponseCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import com.sike.netty.im.server.service.BeanFactory;
import com.sike.netty.im.server.service.GroupService;
import com.sike.netty.im.server.service.SessionService;
import com.sike.netty.im.server.service.UserInfoCache;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 群聊请求 handler
 *
 * @author chenssy
 * @date 2023/09/23
 */
@Slf4j
public class GroupChatRequestHandler extends SimpleChannelInboundHandler<GroupChatRequestCommand> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestCommand msg) throws Exception {
        log.info("收到群发消息:{}", JSONUtil.toJsonStr(msg));
        // 获取所有成员
        GroupService groupService = (GroupService) BeanFactory.getServiceBean(GroupService.class);
        Map<String,Object> groupInfo = groupService.getGroupInfo(msg.getGroupId());

        SessionService sessionService = (SessionService) BeanFactory.getServiceBean(SessionService.class);
        // 发送消息用户
        String fromUserId = sessionService.getUserIdByChannel(ctx.channel());
        String fromUserName = UserInfoCache.getUserInfoByUserId(fromUserId).getUserName();
        // 过滤当前用户
        List<String> memberList = ((List<String>) groupInfo.get("memberList")).stream()
                .filter(x -> !x.equals(fromUserName))
                .collect(Collectors.toList());

        // 通知成员
        List<Channel> channelGroup = new ArrayList<>(memberList.size());
        for (String userName : memberList) {
            // 获取在线的连接
            Channel channel = sessionService.getChannelByUserId(UserInfoCache.getUserInfoByUserName(userName).getUserId());
            if (channel != null) {
                channelGroup.add(channel);
            }
        }

        // 发送消息
        GroupChatResponseCommand responseCommand = new GroupChatResponseCommand((String) groupInfo.get("groupId"), (String) groupInfo.get("groupName"),fromUserName,msg.getMessage());
        Message message = MessageBuilder.buildMessage(responseCommand,null,null);
        for (Channel channel : channelGroup) {
            log.info("{}，发送消息:{}",channel,JSONUtil.toJsonStr(message));
            channel.writeAndFlush(message);
        }
    }
}
